import { Module, Global } from '@nestjs/common';
import { RedisService } from './redis.service';
import { createClient } from 'redis';
import { ConfigService } from '@nestjs/config';

@Global() //  @Global() 把它声明为全局模块，这样只需要在 AppModule 里引入，别的模块不用引入也可以注入
@Module({
  providers: [
    RedisService,
    {
      provide: 'REDIS_CLIENT',
      inject: [ConfigService],
      async useFactory(config: ConfigService) {
        const client = createClient({
          socket: {
            host: config.get('redis.host'),
            port: config.get('redis.port'),
          },
          database: config.get('redis.database'),
        });

        await client.connect();

        return client;
      },
    },
  ],
  exports: [RedisService],
})
export class RedisModule {}
